package com.markhsiu.minimq.core.constant;

import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 常量工具
 * Created by Mark Hsiu on 2017/2/8.
 */
public class ConstantUtil {


    /**
     * I/O线程数经验值是[CPU核数 + 1，CPU核数*2 ]之间
     * 当前系统的进程*2
     */
    private static int workerThreads = Runtime.getRuntime().availableProcessors() ;
    private static final ExecutorService pools = Executors.newFixedThreadPool(2 * workerThreads);

    public static  final  int TIMEOUT = 10000;//10s
    
    /**
     * TCP层面的发送缓冲区大小设置
     */
    public static final int socketSndBufSize = 1024 * 64;//64k
    /**
     * TCP层面的接收缓冲区大小设置
     */
    public static final int socketRcvBufSize = 1024 * 64;//64k
    

    public static int getWorkerThreads() {
        return workerThreads;
    }

    public static void setWorkerThreads(int workers) {
        workerThreads = workers;
    }
    
    public static void threadPools(Runnable command) {
    		pools.execute(command);
    }
    
    public static String UUID() {
		String s = UUID.randomUUID().toString();
		return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18)
				+ s.substring(19, 23) + s.substring(24);
	}
    
    public static <T> T checkNotNull(T reference) {
        if (reference == null) {
          throw new NullPointerException();
        }
        return reference;
      }
    
    public static void checkArgument(
    	      boolean expression,
    	      String errorMessageTemplate,
    	      Object... errorMessageArgs) {
    	    if (!expression) {
    	      throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
    	    }
    	  }
    
    
    static String format(String template,  Object... args) {
        template = String.valueOf(template); // null -> "null"

        // start substituting the arguments into the '%s' placeholders
        StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
        int templateStart = 0;
        int i = 0;
        while (i < args.length) {
          int placeholderStart = template.indexOf("%s", templateStart);
          if (placeholderStart == -1) {
            break;
          }
          builder.append(template.substring(templateStart, placeholderStart));
          builder.append(args[i++]);
          templateStart = placeholderStart + 2;
        }
        builder.append(template.substring(templateStart));

        // if we run out of placeholders, append the extra args in square braces
        if (i < args.length) {
          builder.append(" [");
          builder.append(args[i++]);
          while (i < args.length) {
            builder.append(", ");
            builder.append(args[i++]);
          }
          builder.append(']');
        }

        return builder.toString();
      }
    
    
    
}
